package gae.google.tcserver.servlets;

import gae.google.tcserver.api.CreateJson;

import java.io.IOException;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;
 
import java.util.logging.Logger;

@SuppressWarnings("serial")
public class ListenForRestClientServlet extends HttpServlet
{
	private static final Logger log = Logger.getLogger(LoginServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
    {
        String message = "NONE";
        String command = null;
        String teamId = null;
        Key teamKeyId;
 
        resp.setContentType("text/plain");
 
        if (req.getParameterMap().containsKey("message")){
			CreateJson createJson = new CreateJson();
            message = req.getParameter("message");
            log.warning("MESSAGE: " + message);
    		try {
				JSONObject jsonObject = new JSONObject(message);
				JSONObject ordersObject = jsonObject.getJSONObject("orders");
				JSONObject order = ordersObject.getJSONObject("order");
				command = order.getString("command");
				if (command.contains("getteams")){
					log.warning("GET TEAMS");
					message = createJson.getTeams();
				}else if (command.contains("getmembers")){
					teamId = order.getString("key");
					// convert team id from String to Key
					log.warning("GET MEMBERS: " + teamId);
					teamKeyId = KeyFactory.stringToKey(teamId);
					message = createJson.getTeamMembers(teamKeyId);
				}else{
					message = "Invalid JSON";
				}
    		}catch(JSONException e) {
    		}
		}
        log.warning("MESSAGE: " + message);
        resp.getWriter().println(message);
    }
}